package edu.hawaii.ics.pjdb.util;

import java.util.HashMap;

public class CountingMap<T> extends HashMap<T, Integer> {
    private static final long serialVersionUID = -4970554527140264958L;

    public CountingMap() {
        super();
    }

    public CountingMap(Iterable<T> initials) {
        for (T value : initials) {
            add(value);
        }
    }

    public void add(T value) {
        if (!containsKey(value)) {
            put(value, 1);
        } else {
            put(value, get(value) + 1);
        }
    }

    @Override
    public Integer remove(Object _value) {
        T value = (T) _value;
        int newValue = get(value) - 1;

        if (newValue == 0) {
            remove(value);
        } else {
            put(value, newValue);
        }

        return newValue;
    }
}
